﻿$(function () {
    var provinceList = [];
    //$("#ee").boxDrop({});
    //$("#ee").boxDrop("ss",22);
    $.fn.boxDrop = function (options, param) {
        if (typeof options == 'string') {
            return $.fn.boxDrop.methods[options](this, param);
        }
        var e = this;
        var defaults = {
            // 
            shop_height: 150,//店铺列表的高度
            placeholder: "选择店铺",
            width: 250,
            height: 32,
            outerBoxOverflow: true,//在父级节点把overflow改成visible ,如果父级加hidden，弹出框是给隐藏的
            isRadio: false //是否单选
        };
        var options = $.extend(defaults, options);
        // console.log(options);
        return this.each(function () {

            var $this = $(this);
            // console.log(options.width)
            if ($this.attr("placeholder")) {
                options.placeholder = $this.attr("placeholder");
            }
            var tpl = '<div class="boxDrop"><div class="boxSearch"><span class="key_word">选择店铺</span><em class="pull-left"><i class="fa fa-navicon"></i></em><a class="pull-right ico btn_search"href="javascript:void(0)"><i class="fa fa-angle-double-down"></i></a></div><div class="search_form_box"hidden><h3><a class="btn_close pull-right"><i class="fa fa-times-circle"></i></a>选择店铺</h3><div class="search_filter clearfix"><form class="form-inline "><div class="form-group p-xxs"><label for="exampleInputName2">商品区域</label><div class="input-group"><select  class="form-control  input-sm m-n p-xxs form-search-commodity"style="width: 100px;" multiple></select></div></div><div class="form-group p-xxs"><label for="exampleInputName2">省份</label><div class="input-group"><select class="form-control input-sm  m-n p-xxs form-search-province"style="width: 138px;" multiple><option value="">请选择</option></select></div></div><div class="form-group p-xxs"><label for="exampleInputName2">城市</label><div class="input-group"><select class="form-control input-sm  m-n p-xxs form-search-city"style="width: 117px;" multiple><option value="">请选择</option></select></div></div><div class="form-group p-xxs"><label for="exampleInputName2">零售分部</label><div class="input-group"><select class="form-control input-sm m-n p-xxs  form-search-salePart"style="width: 100px;"><option value="">请选择</option></select></div></div><div class="form-group p-xxs"><label for="exampleInputName2">店铺</label><div class="input-group"><input type="text"class="form-control input-sm form-search-shop"placeholder="请输入店铺/店铺代码"style="width:283px "/></div></div></form></div><div class="select_btn_box clearfix"><button type="button"class="btn btn-xs btn-primary pull-right m-xxs form-btn-ok">确定</button><button type="button"class="btn btn-xs btn-primary pull-right m-xxs form-btn-search">查询</button><button type="button"class="btn btn-xs btn-danger pull-right m-xxs form-btn-inverse">反选</button><button type="button"class="btn btn-xs btn-warning pull-right m-xxs form-btn-selectAll">全选</button></div><div class="select_tab"><table class="table table-striped table-bordered"></table><div class="no-data"><i class="fa fa-file"></i>无数据</div><div class="f-loading"><i class="fa fa-spinner fa-spin fa-3x fa-fw"></i></div></div></div></div>';

            var $boxDrop;
            if (!$this.next().hasClass("boxDrop"))
                $boxDrop = $(tpl).insertAfter(this);
            else {
                return;
                $boxDrop = $this.next();
            }



            $this.hide();
            var $boxSearch = $boxDrop.find('.boxSearch');
            var $lineSearchbg = $boxDrop.nextAll().find('.lineSearchbg');
            var $search_form_box = $boxDrop.find(".search_form_box");

            $boxDrop.find(".select_tab").height(options.shop_height);

            //console.log("23")
            //console.log(x.left)


            //设置宽 高
            $boxSearch.width(options.width);
            $boxSearch.height(options.height)

            //生定位
            $search_form_box.css("top", $boxSearch.outerHeight() - 1);
            var reset = function () {
                var docWidth = $(document).width();
                var x = $boxSearch.offset();
                //console.log(x.top);
                if (x.left >= docWidth / 2) {
                    $search_form_box.css("right", 0);
                    $search_form_box.css("left", "auto");
                } else {
                    $search_form_box.css("left", 0);

                }
            }

            reset();
            $(window).on("resize", function () {
                reset();
            });
            $boxSearch.find(".key_word").width(options.width - 10 - parseInt($boxSearch.find(".key_word").css("left")));

            var $commodity = $boxDrop.find('.form-search-commodity');
            var $province = $boxDrop.find('.form-search-province');
            var $city = $boxDrop.find('.form-search-city');
            var $salePart = $boxDrop.find(".form-search-salePart");
            var $shop = $boxDrop.find(".form-search-shop");
            var $shopTable = $boxDrop.find(".select_tab table");
            var $close = $boxDrop.find(".btn_close");
            var $loading = $boxDrop.find(".f-loading");
            var $searchBtn = $boxDrop.find(".form-btn-search");
            var $inverse = $boxDrop.find(".form-btn-inverse");
            var $selectAll = $boxDrop.find(".form-btn-selectAll");
            var $ok = $boxDrop.find(".form-btn-ok");
            var $select_btn_box = $boxDrop.find(".select_btn_box ");

            $commodity.selectpicker({ 'title': '请选择' });
            $province.selectpicker({ 'title': '请选择' });
            $city.selectpicker({ 'title': '请选择' });


            var ParentAreaID,ProID,CityID,Keys,SalePart;
            //零售区域列表
            commonUtil.bindBasOperationArea(['.form-search-salePart']);
            //获取商品区域
            commonUtil.bindDwGlobalVariables2({ dictValue: '商品区域' }, ['select.form-search-commodity'], function () {
                $commodity.selectpicker('refresh');
            });

            //选择商品区域
            $commodity.on('hidden.bs.select', function () {
                var t = $commodity.val();
                if (t != null && t != "") {
                    $this.boxDrop.methods.loadAreaList($(this).val(), provinceList, $province, $city,function() {
                        $province.selectpicker('refresh');
                        $city.empty();
                        $city.append('<option value="">请选择</option>');
                        $city.selectpicker('refresh');
                    });
                }
            });
            //$boxDrop.find('.form-serarch-commodity').on('change', '#serarch-commodity-2', function () {
            //    loadAreaList($(this).val(), provinceList2, $('#serarch-province-2'), $('#serarch-city-2'));
            //});

            //选择省份
            $province.on('change', function () {
                $city.empty();
                //$city.append('<option value="">请选择</option>');
                var _this = $(this);
                provinceList.map(function (item) {
                    var r = $.inArray(item[0].ParentID, _this.val());
                    if (r != -1) {
                        console.log(_this.val());
                        item.map(function (city) {
                            $city.append('<option value="' + city.AreaID + '">' + city.AreaName + '</option>');
                        });
                        $city.selectpicker('refresh');
                        $city.val('');
                        //return false;
                    }
                });
            });


            //打开
            $boxSearch.on("click", function () {

                var _this = $(this);
                //点击本身显示隐藏
                if (_this.hasClass('boxSearchHover')) {
                    if (options.outerBoxOverflow && $this.parent().css("overflow") == "visible") {
                        $this.parent().css("overflow", "hidden");
                    }
                    //  $this.close();
                    closeBox();


                } else {
                    //  $this.boxDrop.methods.open(e)
                    if (options.outerBoxOverflow && $this.parent().css("overflow") == "hidden") {
                        $this.parent().css("overflow", "visible");
                    }
                    shopBox();





                }
                $(document).on('click', function (event) {
                    var event = window.event || event;
                    if (!$(event.target).parent().hasClass('boxSearch') && !$(event.target).hasClass('boxSearch') && !$(event.target).parent().parent().hasClass('boxSearch') &&
                        $(event.target).parents(".search_form_box").length == 0
                        ) {
                        closeBox();
                    }
                });

            });


            //打开选中条件
            if (!$.isEmptyObject(options.params)) {//ParentAreaID，ProID,CityID, Keys, SalePart

            }

            //关闭
            $close.on("click", function () {
                closeBox();
            });

            //查询
            $searchBtn.on("click", function () {
                $(this).attr("data-firstClick", 1);
                search();
            });



            //反选 
            $inverse.on("click", function () {
                $shopTable.find("a.shop_check").each(function (i, obj) {

                    checkbox($(this));
                });
            });
            //全选 
            $selectAll.on("click", function () {
                $shopTable.find("a.shop_check").each(function (i, obj) {
                    checkbox($(this), 1);
                });

            });

            //ok
            $ok.on("click", function () {
                var codes = getCheckbox();
                var names = getCheckboxName();
                $this.val(codes);
                $boxSearch.prop("title", names);
                if (codes != "") {
                    $boxSearch.find(".key_word").text(names);

                } else {
                    $boxSearch.find(".key_word").text(options.placeholder);

                }
                closeBox();
                //  console.log(codes)

            });
            //checkbox 选择取消操作
            var checkbox = function ($checkbox, isall) {
                if (isall == 1) {
                    $checkbox.attr("data-check", 1);
                    $checkbox.find("i").removeClass("fa-square-o");
                    $checkbox.find("i").addClass("fa-check-square");
                } else {
                    if ($checkbox.attr("data-check") == 1) {
                        $checkbox.attr("data-check", 0);
                        $checkbox.find("i").removeClass("fa-check-square");
                        $checkbox.find("i").addClass("fa-square-o");
                    } else {
                        $checkbox.attr("data-check", 1);
                        $checkbox.find("i").removeClass("fa-square-o");
                        $checkbox.find("i").addClass("fa-check-square");

                    }
                }
            }
            var unCheck = function ($checkbox) {
                $checkbox.attr("data-check", 0);
                $checkbox.find("i").removeClass("fa-check-square");
                $checkbox.find("i").addClass("fa-square-o");
            }
            //checkbox 获取选择的店铺
            var getCheckbox = function () {
                var $checkObj = $shopTable.find("a.shop_check[data-check=1]");
                var codes = [];
                $checkObj.each(function (i) {
                    var _ShopID = $(this).attr("data-ShopID");
                    codes.push(_ShopID);
                });
                return codes.join(",");
            };
            //checkbox 获取选择的店铺名称
            var getCheckboxName = function () {
                var $checkObj = $shopTable.find("a.shop_check[data-check=1]");
                var codes = [];
                $checkObj.each(function (i) {
                    var _ShopName = $(this).attr("data-ShopName");
                    codes.push(_ShopName);
                });

                return codes.join(",");
            };
            //checkbox 获取没选择的店铺
            var getUnCheckbox = function () {
                var $checkObj = $shopTable.find("a.shop_check[data-check=0]");
                var codes = [];
                $checkObj.each(function (i) {
                    var _ShopID = $(this).attr("data-ShopID");
                    codes.push(_ShopID);
                });
                return codes.join(",");
            };

            var closeBox = function () {

                $boxSearch.removeClass('boxSearchHover');
                $boxSearch.find('.btn_search i').addClass("fa-angle-double-down");
                $boxSearch.find('.btn_search i').removeClass("fa-angle-double-up");
                $search_form_box.hide();
                $this.trigger("boxdrop_close");
            };
            var shopBox = function () {
                $boxSearch.addClass('boxSearchHover');
                $boxSearch.find('.btn_search i').addClass("fa-angle-double-up");
                $boxSearch.find('.btn_search i').removeClass("fa-angle-double-down");
                $search_form_box.show();
                $this.trigger("boxdrop_open");

            };
            var search = function () {
                ParentAreaID = $commodity.val();
                ProID = $province.val();
                CityID = $city.val();
                Keys = $shop.val();
                SalePart = $salePart.val();
                $shopTable.html("");
                $loading.show();
                $select_btn_box.find("button").attr("disabled", true);
                Y.API2('DwShop', 'GetShopListByConditions2', {
                    ParentAreaID: ParentAreaID,
                    ProID: ProID,
                    CityID: CityID,
                    SalePart: SalePart,
                    Keys: Keys
                }, function (data) {
                    $select_btn_box.find("button").attr("disabled", false);
                    $boxDrop.find(".no-data").hide();
                    $loading.hide();
                    if (data.Success == false) {
                        swal(data.Message, '', 'error');
                        $boxDrop.find(".no-data").show();
                    }
                    else {
                        if (data.length > 0) {
                            //fa-check-square-o
                            $.each(data, function (i, obj) {
                                if (i % 2 == 0) {//左
                                    var newRow = '<tr><td data-index="' + i + '" class="groupData' + i + '"><a data-check="0" data-ShopCode="' + obj.ShopCode + '"  data-ShopID="' + obj.ShopID + '"   data-ShopName="' + obj.ShopName + '"  href="javascript:;" class="shop_check"><i class="fa fa-square-o"></i></a></td><td  data-index="' + i + '"  class="groupData' + i + '">' + obj.ShopCode + '</td><td  data-index="' + i + '"  class="groupData' + i + '">' + obj.ShopName + '</td><td data-index="' + (i + 1) + '"  class="groupData' + (i + 1) + '"></td><td data-index="' + (i + 1) + '" class="groupData' + (i + 1) + '"></td><td data-index="' + (i + 1) + '" class="groupData' + (i + 1) + '"></td></tr>';
                                    //$shopTable.html(newRow);
                                    $(newRow).appendTo($shopTable);
                                } else {//右
                                    $shopTable.find("tr:last").find("td:eq(3)").html('<a data-check="0"  data-ShopCode="' + obj.ShopCode + '" data-ShopID="' + obj.ShopID + '"   data-ShopName="' + obj.ShopName + '"  href="javascript:;" class="shop_check"><i class="fa fa-square-o"></i></a>');
                                    $shopTable.find("tr:last").find("td:eq(4)").html(obj.ShopCode);
                                    $shopTable.find("tr:last").find("td:eq(5)").html(obj.ShopName);
                                }


                            });
                            //选择和取消
                            $shopTable.find("td").on("click", function () {
                                console.log(this)
                                var index = $(this).attr("data-index");
                                var $checkbox = $shopTable.find(".groupData" + index).find("a[data-check]");
                                if (options.isRadio)//单选 取消所有
                                {
                                    $shopTable.find("a.shop_check").each(function (i, obj) {
                                        unCheck($(this));
                                    });
                                }
                                checkbox($checkbox);
                            });
                        } else {
                            $boxDrop.find(".no-data").show();
                        }
                    }
                });
            }


        });

    }
    $.fn.boxDrop.methods = {
        search: function (e) {
            var $this = $(e);
            var $boxDrop = $this.next(".boxDrop");
            var $boxSearch = $boxDrop.find('.boxSearch');
            var $searchBtn = $boxDrop.find(".form-btn-search");
            $searchBtn.trigger("click");
        },
        load: function (e, param) {//  {ParentAreaID:"",ProID:"",CityID:"",SalePart:"",Keys:"" ,firstLoad:true},//ParentAreaID， ProID,CityID, Keys, SalePart 定制初始参数 firstLoad true 第一次加载
            var $this = $(e);
            var _this = this;
            var $boxDrop = $this.next(".boxDrop");
            var $boxSearch = $boxDrop.find('.boxSearch');
            $boxSearch.addClass('boxSearchHover');
            $boxSearch.find('.btn_search i').addClass("fa-angle-double-up");
            $boxSearch.find('.btn_search i').removeClass("fa-angle-double-down");
            var $search_form_box = $boxDrop.find(".search_form_box");
            $search_form_box.show();

            var $commodity = $boxDrop.find('.form-search-commodity'),
             $province = $boxDrop.find('.form-search-province'),
             $city = $boxDrop.find('.form-search-city'),
            $salePart = $boxDrop.find(".form-search-salePart"),
            $shop = $boxDrop.find(".form-search-shop"),
            $searchBtn = $boxDrop.find(".form-btn-search");

            if (!_this.checkNull(param.SalePart)) {
                $salePart.val(param.SalePart);
            }
            if (!_this.checkNull(param.Keys)) {
                $shop.val(param.Keys);
            }
            if (!_this.checkNull(param.ParentAreaID)) {
                $commodity.val(param.ParentAreaID);
                // console.log(param.ParentAreaID)
                this.loadAreaList(param.ParentAreaID, provinceList, $province, $city, function () {
                    //  console.log(22)
                    if (!_this.checkNull(param.ProID)) {
                        $province.val(param.ProID);
                        //选择商品区域
                        $city.empty();
                        $city.append('<option value="">请选择</option>');

                        provinceList.map(function (item) {
                            if (item[0].ParentID == param.ProID) {

                                item.map(function (city) {
                                    $city.append('<option value="' + city.AreaID + '">' + city.AreaName + '</option>');
                                });
                                $city.val('');
                                return false;
                            }
                        });

                        if (!_this.checkNull(param.CityID)) {
                            $city.val(param.CityID);
                        }
                        if (!_this.checkNull(param.firstLoad) && !param.firstLoad) {
                            //第一次不加载 操作
                        } else {
                            //第一次加载 操作
                            if ($searchBtn.attr("data-firstClick") != 1) {
                                $searchBtn.click();
                            }
                        }

                    }

                });
            }

            if (_this.checkNull(param.ProID))//省份是空时可以直接查询，否则要在省份ajax获取后再回调查询
            {
                if (!_this.checkNull(param.firstLoad) && !param.firstLoad) {
                    //第一次不加载 操作
                } else {
                    //第一次加载 操作
                    if ($searchBtn.attr("data-firstClick") != 1) {
                        $searchBtn.click();
                    }
                }
            }
        },
        checkNull: function (obj) {
            return typeof (obj) == 'undefined' || obj == null || obj == "";
        },
        open: function (e, param) {

            var $this = $(e);
            var $boxDrop = $this.next(".boxDrop");
            var $boxSearch = $boxDrop.find('.boxSearch');
            $boxSearch.addClass('boxSearchHover');
            $boxSearch.find('.btn_search i').addClass("fa-angle-double-up");
            $boxSearch.find('.btn_search i').removeClass("fa-angle-double-down");
            var $search_form_box = $boxDrop.find(".search_form_box");
            $search_form_box.show();

            if (!this.checkNull(param)) {
                this.load(e, param)
            }
            $this.trigger("boxdrop_open");
            // console.log(param);
        },
        close: function (e, param) {

            var $this = $(e);
            var $boxDrop = $this.next(".boxDrop");
            var $boxSearch = $boxDrop.find('.boxSearch');
            $boxSearch.removeClass('boxSearchHover');
            $boxSearch.find('.btn_search i').addClass("fa-angle-double-down");
            $boxSearch.find('.btn_search i').removeClass("fa-angle-double-up");
            var $search_form_box = $boxDrop.find(".search_form_box");
            $search_form_box.hide();
            // console.log(param);
            $this.trigger("boxdrop_close");
        },
        loadAreaList: function (value, arr, el, el2, callback) {
            var _this = this;
            el.empty();
            //el.append('<option value="">请选择</option>');
            el2.empty();
            //el2.append('<option value="">请选择</option>');
            if (_this.checkNull(value))
                return false;

            var ids = value.join(",");
            console.log(ids);
            Y.API2('OdsErpBasArea', 'GetOdsErpBasAreaList2', {
                Param: 1,
                DistrictIDs: ids
            }, function (data) {
                if (data.Success == false) {
                    swal(data.Message, '', 'error');
                } else {
                    data.map(function (item) {
                        arr.push(item);
                        el.append('<option value="' + item[0].ParentID + '">' + item[0].ParentName + '</option>');
                    });
                    // console.log(arr)



                    if (!_this.checkNull(callback))
                        callback();
                }
            });
        }

    };

});